﻿using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using DevHub.WindowsApp.Dialogs;
using FluentAvalonia.UI.Controls;
using NetEasyMusic.Lib.Models;

namespace DevHub.WindowsApp.Pages.Music;

public partial class NetEasyMusicView : UserControl
{

    public NetEasyMusicView()
    {
        InitializeComponent();
        SearchBox = this.FindControl<TextBox>("SearchBox");
        ResultList = this.FindControl<ListBox>("ResultList");
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private async void SearchKeyDown(object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;
        if (string.IsNullOrEmpty(SearchBox.Text)) return;
        var a = new NetEasyMusic.Lib.Data.Search();
        ResultList.ItemsSource = await a.SearchContext(SearchBox.Text);
    }

    private async void ResultTapped(object? sender, TappedEventArgs e)
    {
        if (sender is not Control control) return;
        if (control.DataContext is not SongModel model) return;
        var td = new TaskDialog
        {
            Title = "DevHub",
            Content = new SongDialog(model),
            FooterVisibility = TaskDialogFooterVisibility.Never,
            Buttons =
            {
                new TaskDialogButton("复制", true),
                new TaskDialogButton("返回", false)
            },
            XamlRoot = (Visual)VisualRoot!
        };
        td.Closing += (dialog, args) =>
        {
            if (!(bool)args.Result) return;
            if (dialog.Content is not SongDialog song) return;
            song.CopyInfo();
        };
        await td.ShowAsync();
    }
}